package com.northpool.operator.common.net;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

@OperatorInfo(
    ref = "NetworkCheckOperator",
    name = "网络连通性检测",
    description = "检测指定IP和端口的网络连通性"
)
@OutputParams({
    @OutputParam(ref = "result", name = "检测结果", desc = "是否可达（true/false）")
})
public class NetworkCheckOperator extends StpOperatorHelper {

    @InputParams({
        @InputParam(ref = "ip", name = "IP地址", desc = "目标IP地址，示例: 192.168.164.45", required = true),
        @InputParam(ref = "port", name = "端口号", desc = "目标端口，示例: 8011", required = true)
    })
    public NetworkCheckOperator() {
        super();
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(NetworkCheckOperator.class, TestParamBuilder.aBuilder()
            .param("ip", "192.168.164.45")
            .param("port", "8021")
            .build());
    }

    @Override
    public void execute(ParamTool params) throws Exception {
        String ip = params.getStr("ip");
        String portStr = params.getStr("port");

        if (StrUtil.isBlank(ip) || StrUtil.isBlank(portStr)) {
            this.error("IP和端口不能为空");
            this.failedExit();
        }

        int port;
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            this.error("端口格式错误: " + portStr);
            this.failedExit();
            return;
        }

        boolean isReachable = checkNetwork(ip, port);
        this.result("result", isReachable);
    }

    /**
     * TCP端口连通性检测
     * @param timeout 超时时间（毫秒），默认3秒
     */
    private boolean checkNetwork(String ip, int port, int timeout) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, port), timeout);
            return true;
        } catch (IOException e) {
            this.error("连接失败: " + ExceptionUtil.getMessage(e));
            return false;
        }
    }

    // 重载方法设置默认超时时间
    private boolean checkNetwork(String ip, int port) {
        return checkNetwork(ip, port, 3000); // 默认3秒超时
    }
}
